package org.example.rocketmq.batch;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 批量发送消息
 */
public class Producer {

    public static void main(String[] args) throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
        asyncSend();
    }

    public static DefaultMQProducer getProducer() {
        //1.创建生产者producer，并指定组名
        DefaultMQProducer producer = new DefaultMQProducer("producer-group1");
        //2.指定nameserver
        producer.setNamesrvAddr("192.168.3.109:9876;192.168.3.108:9876");
        return producer;
    }

    /**
     * 发送同步消息
     */
    public static void asyncSend() throws MQClientException, RemotingException, InterruptedException, MQBrokerException {
        //1.创建生产者producer，并指定组名
        DefaultMQProducer producer = getProducer();
        //3.启动producer
        producer.start();

        List<Message> messages = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            //4.创建消息对象，指定topic tag 消息体
            /**
             * 参数
             *  1. topic
             *  2. tag
             *  3. content消息体
             */
            Message message = new Message("batchMsg", "tag1", ("hello world " + i).getBytes());
            messages.add(message);
        }
        //5.发送消息
        SendResult result = producer.send(messages);
        //发送状态
        SendStatus status = result.getSendStatus();
        //消息ID
        String msgId = result.getMsgId();
        //接收消息的队列ID
        int queueId = result.getMessageQueue().getQueueId();

        System.out.println("result ==> status:" + status + " msgId:" + msgId + " queueId:" + queueId);
        //休眠1s
        TimeUnit.SECONDS.sleep(1);

        //6.关闭生产者
        producer.shutdown();
    }
}
